package com.legal.app.common;
/**
 * @author Ale
 * @description
 * @date 2025/6/18 10:27
 */

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import lombok.Setter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;
import com.legal.app.domain.User;


/**
 * 自定义登录用户对象，适配项目中的User实体
 */
@Data
public class LoginUser implements UserDetails, Serializable {

    private static final long serialVersionUID = 1L;

    /** 用户主键ID */
    private Long userId;

    /** 用户信息实体 */
    private User user;

    /** 权限列表 */
    private List<String> permissions;



    /**
     * 用户唯一标识
     */
    @Setter
    private String token;

    /**
     * 登录时间
     */
    private Long loginTime;

    /**
     * 过期时间
     */
    private Long expireTime;

    /**
     * 登录IP地址
     */
    private String ipaddr;

    /**
     * 登录地点
     */
    private String loginLocation;

    /**
     * 浏览器类型
     */
    private String browser;




    /** 登录凭证 */
    private Long userType;

    private String username;


    public LoginUser() {
    }

    public LoginUser(User user, List<String> permissions) {
        this.user = user;
        this.permissions = permissions;
        this.userId = user.getId();
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // 空值保护：若权限列表为空，根据用户类型生成默认权限
        if (permissions == null || permissions.isEmpty()) {
            permissions = generatePermissionsByUserType();
        }

        return permissions.stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
    }

    /**
     * 根据用户类型生成默认权限（基于数据字典中的user_type定义）
     */
    private List<String> generatePermissionsByUserType() {
        List<String> defaultPermissions = new ArrayList<>();
        Long userType = (long) Math.toIntExact(user != null ? user.getUserType() : 1);
        // 默认为普通用户

        if (userType == 1) {
            // 普通用户
            defaultPermissions.addAll(Arrays.asList(
                    "user:mine",
                    // 查看个人信息
                    "case:query",
                    // 查询法律援助案件
                    "lawyer:list",
                    // 浏览律师列表
                    "lawyer:query",
                    "lawyer:details"
            ));
        } else if (userType == 2) {// 律师
            defaultPermissions.addAll(Arrays.asList(
                    "user:mine",
                    "lawyer:query",
                    // 查看个人律师信息
                    "case:accept",
                    // 接受案件指派
                    "message:reply",
                    // 回复用户咨询
                    "service:price"
                    // 设置服务价格
            ));
        } else if (userType == 3) {// 管理员
            defaultPermissions.addAll(Arrays.asList(
                    "admin:user:manage",
                    // 管理用户账号
                    "admin:lawyer:audit",
                    // 审核律师资质
                    "admin:case:assign",
                    // 指派案件
                    "system:config"
                    // 系统配置管理
            ));
        } else {
            defaultPermissions.add("user:view");
        }

        return defaultPermissions;
    }

    @JsonIgnore
    @Override
    public String getPassword() {
        return user.getEncodeCipher();
    }

    @Override
    public String getUsername() {
        return user.getNickName();
    }

//    @Override
//    public String getUsername() {
//        return user.getNickName();
//    }

    /**
     * 账户是否未过期,过期无法验证
     */
    @JsonIgnore
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    /**
     * 指定用户是否被锁定,锁定的用户无法进行身份验证
     * @return
     */
    @JsonIgnore
    @Override
    public boolean isAccountNonLocked() {
        return user.getStatus() == 1; // 1表示正常状态
    }

    /**
     * 指示是否已过期的凭据,过期的凭据防止认证
     * @return
     */
    @JsonIgnore
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    /**
     * 是否可用 ,禁用的用户不能身份验证
     * @return
     */
    @JsonIgnore
    @Override
    public boolean isEnabled() {
        return user.getStatus() == 1; // 1表示正常状态
    }

    // Getter和Setter方法
    public Long getUserId() {
        return userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public List<String> getPermissions() {
        return permissions;
    }

    public void setPermissions(List<String> permissions) {
        this.permissions = permissions;
    }

    public String getToken() {
        return token;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        LoginUser that = (LoginUser) o;
        return Objects.equals(userId, that.userId);
    }

    @Override
    public int hashCode() {
        return Objects.hash(userId);
    }

    public void setUserType(Long userType) {
        this.userType = userType;
    }
    public Long getUserType() {
        return userType;
    }

    public void serUsername(String username) {
    	this.username = user.getNickName();
    }


}